﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Mail;
using EFFC.Net.Common;

namespace EFFC.Net.ResourceLib.Parameters
{
    [Serializable]
    public class EmailAttachCollection:List<Attachment>
    {
        public EmailAttachCollection()
        {
        }
        /// <summary>
        /// 添加多個文件路徑，如果文件不存在則拋出異常FileNotFoundException
        /// </summary>
        /// <param name="files">多個文件路徑</param>
        /// <param name="split">每個文件路徑之間分割符</param>
        public new void Add(string files, char split)
        {
            if (!string.IsNullOrEmpty(files))
            {
                string[] ss = files.Split(split);
                foreach (string s in ss)
                {
                    AddFile(s);
                }
            }
        }
        /// <summary>
        /// 添加單個文件,如果文件不存在則拋出異常FileNotFoundException
        /// </summary>
        /// <param name="file">文件路徑</param>
        public new void Add(string file)
        {
            AddFile(file);
        }
        /// <summary>
        /// 添加多個文件路徑,如果文件不存在則拋出異常FileNotFoundException
        /// </summary>
        /// <param name="files">文件名稱</param>
        /// <param name="split">多個文件名稱的分隔符</param>
        /// <param name="rootpath">多個文件所在的目录</param>
        public new void Add(string files, char split, string rootpath)
        {
            if (!string.IsNullOrEmpty(files))
            {
                string[] ss = files.Split(split);
                foreach (string s in ss)
                {
                    string path = rootpath + s;
                    AddFile(path);
                }
            }
        }

        private void AddFile(string file)
        {
            if (File.Exists(file))
            {
                Attachment ach = new Attachment(file);
                FileInfo fi = new FileInfo(file);
                //此處必須用gb2132進行原碼錶示，用big5也識別不了
                string filename = ComFunc.ConvertEncode(fi.Name, Encoding.Default, Encoding.UTF8);
                ach.NameEncoding = Encoding.UTF8;
                //进行base64转化
                string base64FileName = "=?" + Encoding.UTF8.HeaderName + "?B?" + Convert.ToBase64String(Encoding.UTF8.GetBytes(filename)) + "?=";
                ach.ContentDisposition.FileName = base64FileName;
                ach.ContentType.CharSet = Encoding.UTF8.HeaderName;

                ach.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                ach.ContentDisposition.Inline = false;

                base.Add(ach);
            }
            else
            {
                throw new FileNotFoundException("File " + file + " not Exists");
            }
        }
    }
}
